<template>
    <div class="query-analysis">
        <!-- 分析按钮 -->
        <el-button 
            type="primary" 
            size="small" 
            @click="analyze"
            :loading="isAnalyzing"
            class="analysis-btn"
        >
            <el-icon><DataAnalysis /></el-icon>
            AI分析
        </el-button>

        <!-- 分析结果对话框 -->
        <el-dialog
            v-model="showAnalysisDialog"
            title="AI 分析结果"
            width="60%"
            :close-on-click-modal="false"
            class="analysis-dialog"
            :modal-class="'analysis-dialog-modal'"
            align-center
            :append-to-body="true"
        >
            <template #header="{ close }">
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon><DataAnalysis /></el-icon>
                        <span>AI 分析结果</span>
                    </div>
                    <div class="dialog-tools">
                        <el-button
                            type="primary"
                            size="small"
                            plain
                            @click="copyAnalysis"
                        >
                            <el-icon><DocumentCopy /></el-icon>
                            复制结果
                        </el-button>
                        <el-button
                            type="default"
                            size="small"
                            @click="close"
                        >
                            <el-icon><Close /></el-icon>
                        </el-button>
                    </div>
                </div>
            </template>

            <div v-if="analysis" class="analysis-content">
                <div class="analysis-section">
                    <div class="section-header">
                        <el-tag size="small" type="info">查询语句</el-tag>
                    </div>
                    <pre class="sql-content">{{ props.sql }}</pre>
                </div>

                <div class="analysis-section">
                    <div class="section-header">
                        <el-tag size="small" type="success">分析结果</el-tag>
                        <span v-if="isTyping" class="typing-indicator">
                            <i class="typing-dot"></i>
                            <i class="typing-dot"></i>
                            <i class="typing-dot"></i>
                        </span>
                    </div>
                    <div class="analysis-details" v-html="renderedAnalysis"></div>
                </div>
            </div>
            <div v-else-if="isAnalyzing" class="analyzing-placeholder">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>正在分析数据...</span>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { DataAnalysis, DocumentCopy, Close, Loading } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'

const props = defineProps({
    sql: {
        type: String,
        required: true
    },
    data: {
        type: Array,
        required: true
    },
    columns: {
        type: Array,
        required: true
    }
})

const isAnalyzing = ref(false)
const analysis = ref(null)
const md = new MarkdownIt({
    html: true,
    breaks: true,
    linkify: true
})

// 添加打字机效果相关的状态
const currentText = ref('')
const isTyping = ref(false)
let typingTimer = null

// 打字机效果函数
const typeText = (text) => {
    isTyping.value = true
    let index = 0
    const fullText = text
    currentText.value = ''

    const type = () => {
        if (index < fullText.length) {
            currentText.value += fullText[index]
            index++
            typingTimer = setTimeout(type, 20) // 调整速度
        } else {
            isTyping.value = false
        }
    }

    type()
}

// 修改消息处理函数
const handleWebSocketMessage = (event) => {
    try {
        const data = JSON.parse(event.data)
        if (data.type === 'reply') {
            if (data.messageType === 'content') {
                if (!analysis.value) {
                    analysis.value = {
                        summary: '查询结果分析',
                        details: ''
                    }
                }
                
                // 累积内容
                analysis.value.details += data.content
                // 更新打字机效果
                if (typingTimer) {
                    clearTimeout(typingTimer)
                }
                typeText(analysis.value.details)

                if (data.content === '') {
                    // 分析完成
                    isAnalyzing.value = false
                }
            }
        }
    } catch (error) {
        console.error('处理分析响应出错:', error)
    }
}

// 修改渲染分析结果的计算属性
const renderedAnalysis = computed(() => {
    if (!currentText.value) return ''
    return md.render(currentText.value)
})

// WebSocket连接
let ws = null

// 修改 WebSocket 初始化和消息处理
const initWebSocket = () => {
    try {
        if (ws && ws.readyState === WebSocket.OPEN) {
            sendAnalysisRequest()
            return
        }

        ws = new WebSocket('wss://adminstore.saas.nbsaas.com/websocket')
        
        ws.onopen = () => {
            console.log('WebSocket连接已建立')
            sendAnalysisRequest()
        }
        
        ws.onmessage = handleWebSocketMessage
        
        ws.onerror = (error) => {
            console.error('WebSocket错误:', error)
            isAnalyzing.value = false
            ElMessage.error('AI分析连接失败')
            ws = null
        }
        
        ws.onclose = () => {
            console.log('WebSocket连接已关闭')
            isAnalyzing.value = false
            ws = null
        }
    } catch (error) {
        console.error('WebSocket初始化失败:', error)
        isAnalyzing.value = false
        ElMessage.error('AI分析服务连接失败')
        ws = null
    }
}

// 修改发送分析请求函数
const sendAnalysisRequest = () => {
    const prompt = `请分析以下SQL查询结果数据，提供关键见解和统计信息：
SQL查询: ${props.sql}
数据示例(前5条): ${JSON.stringify(props.data.slice(0, 5), null, 2)}
总记录数: ${props.data.length}
字段列表: ${props.columns.join(', ')}

请提供：
1. 数据概览和基本统计
2. 关键发现和异常值
3. 数据分布特征
4. 潜在的业务见解
`
    const msg = {
        type: 'prompt',
        message: prompt,
        context: 'result_analysis'
    }

    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify(msg))
    }
}

const showAnalysisDialog = ref(false)

// 修改分析方法
const analyze = async () => {
    if (!props.data.length) {
        ElMessage.warning('没有可分析的查询结果')
        return
    }

    isAnalyzing.value = true
    analysis.value = null
    showAnalysisDialog.value = true

    try {
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            initWebSocket()
        } else {
            sendAnalysisRequest()
        }
    } catch (error) {
        console.error('分析查询结果失败:', error)
        ElMessage.error('分析查询结果失败')
        isAnalyzing.value = false
    }
}

// 添加复制功能
const copyAnalysis = () => {
    if (!analysis.value?.details) return
    
    try {
        const text = analysis.value.details
        navigator.clipboard.writeText(text)
        ElMessage.success('分析结果已复制到剪贴板')
    } catch (err) {
        console.error('复制失败:', err)
        ElMessage.error('复制失败')
    }
}

// 组件卸载时清理
onBeforeUnmount(() => {
    if (ws) {
        ws.close()
        ws = null
    }
    if (typingTimer) {
        clearTimeout(typingTimer)
    }
})
</script>

<style scoped>
.query-analysis {
    display: inline-block;
}

.analysis-dialog {
    --el-dialog-padding-primary: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}

.dialog-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
}

.dialog-tools {
    display: flex;
    gap: 8px;
}

.analysis-content {
    padding: 0 20px;
}

.analysis-section {
    margin-bottom: 24px;
}

.section-header {
    margin-bottom: 12px;
}

.sql-content {
    background-color: #f6f8fa;
    padding: 12px;
    border-radius: 4px;
    font-family: monospace;
    margin: 0;
    white-space: pre-wrap;
    word-break: break-all;
}

.analyzing-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 40px 0;
    color: #909399;
}

.analyzing-placeholder .is-loading {
    font-size: 20px;
    animation: rotating 2s linear infinite;
}

@keyframes rotating {
    from {
        transform: rotate(0);
    }
    to {
        transform: rotate(360deg);
    }
}

.analysis-details {
    line-height: 1.6;
    transition: none; /* 移除过渡效果以避免打字机效果卡顿 */
}

.analysis-details :deep(p) {
    margin-bottom: 12px;
}

.analysis-details :deep(ul),
.analysis-details :deep(ol) {
    padding-left: 20px;
    margin-bottom: 12px;
}

.analysis-details :deep(li) {
    margin-bottom: 8px;
}

.analysis-details :deep(code) {
    background-color: #f6f8fa;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
}

.analysis-details :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 16px;
}

.analysis-details :deep(th),
.analysis-details :deep(td) {
    border: 1px solid #dcdfe6;
    padding: 8px;
    text-align: left;
}

.analysis-details :deep(th) {
    background-color: #f5f7fa;
}

:deep(.el-dialog__body) {
    padding: 0;
    margin: 20px 0;
}

:deep(.el-dialog__header) {
    margin: 0;
    padding: 20px 0;
    border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__headerbtn) {
    display: none;
}

/* 添加全局样式，确保模态框在屏幕中间 */
:global(.analysis-dialog-modal) {
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.el-dialog) {
    margin: 0 auto !important;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

.typing-indicator {
    display: inline-flex;
    align-items: center;
    margin-left: 8px;
}

.typing-dot {
    display: inline-block;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background-color: #909399;
    margin: 0 2px;
    animation: typing-animation 1s infinite;
}

.typing-dot:nth-child(2) {
    animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes typing-animation {
    0%, 60%, 100% {
        transform: translateY(0);
        opacity: 0.4;
    }
    30% {
        transform: translateY(-4px);
        opacity: 1;
    }
}
</style> 